﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;

namespace Twinkle.Dialogs.Hashtag
{
    public partial class BindingEditor : Form
    {
        public Twinkle.Data.Config.BehaviorConfig.TagBinding Binding { get; set; }

        public BindingEditor()
        {
            InitializeComponent();
        }

        private string bindingTags = null;

        private void BindingEditor_Load(object sender, EventArgs e)
        {
            if (Binding != null)
            {
                targetText.Text = Binding.Keyword;
                matchType.SelectedIndex = (int)Binding.Type;
                bindingTags = Binding.Tags;
            }
            else
            {
                matchType.SelectedIndex = 0;
            }
            ValidateInput();
        }

        public void ValidateInput()
        {
            try
            {
                if (matchType.SelectedIndex == 4)
                    Regex.Match(String.Empty, targetText.Text);
                else if (string.IsNullOrEmpty(targetText.Text))
                    throw new ApplicationException();
                this.OKBtn.Enabled = true;
                invalidRegexNotify.Visible = false;
            }
            catch
            {
                this.OKBtn.Enabled = false;
                if (matchType.SelectedIndex == 4)
                    invalidRegexNotify.Visible = true;
                else
                    invalidRegexNotify.Visible = false;
            }
        }

        private void targetText_TextChanged(object sender, EventArgs e)
        {
            ValidateInput();
        }

        private void matchType_SelectedIndexChanged(object sender, EventArgs e)
        {
            ValidateInput();
        }

        private void bindingTagEdit_Click(object sender, EventArgs e)
        {
            using (var htSelector = new HashtagSelector(bindingTags))
            {
                htSelector.AutoBindEditable = false;
                if (htSelector.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                    bindingTags = htSelector.Hashtags;
            }
        }

        private void OKBtn_Click(object sender, EventArgs e)
        {
            this.Binding = new Data.Config.BehaviorConfig.TagBinding()
            {
                Keyword = targetText.Text,
                Type = (Data.Config.BehaviorConfig.TagBinding.BindingType)matchType.SelectedIndex,
                Tags = bindingTags
            };
        }


    }
}
